package botserver

import (
	"dingbot/botapi"
	"dingbot/config"
	"dingbot/errhelp"
	"dingbot/global"
	"dingbot/plugin"
	"dingbot/tools"

	"github.com/dingdinglz/dingtools/dingjson"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/websocket/v2"
)

func Start() {
	app := fiber.New()
	app.Use("/", func(c *fiber.Ctx) error {
		if websocket.IsWebSocketUpgrade(c) {
			c.Locals("allowed", true)
			return c.Next()
		}
		return fiber.ErrUpgradeRequired
	})

	app.Get("/", websocket.New(func(c *websocket.Conn) {
		var (
			msg []byte
			err error
		)
		for {
			if _, msg, err = c.ReadMessage(); err != nil {
				errhelp.Tag(err, "read websocket message")
				break
			}
			message_send := string(msg)
			j := dingjson.NewFromBytes(msg)
			post_type, _ := j.GetString("post_type")
			if post_type != "meta_event" {
				global.Logger.Debug(message_send)
			}
			if post_type == "message" {
				message_type, _ := j.GetString("message_type")
				message, _ := j.GetString("message")
				if message_type == "group" {
					group_id_i, _ := j.GetInt("group_id")
					group_id := tools.Int64ToString(group_id_i)
					plugin.GroupMsgDo(plugin.PluginDataGroupMsg{Message: message, Group_id: group_id})
					if message == "关于" {
						botapi.SendGroupMsg(group_id, "dingbot CopyRight by dinglz")
					}
				}
			}
		}

	}))

	go func() {
		global.Logger.Info("正在启动websocket服务器...")
		err := app.Listen(":" + config.GetConfig().Port.WebSocket)
		errhelp.Abort(err, "start websocket server")
	}()
}
